package com.dtguai.web.web.fastDfs.service.impl;

import com.dtguai.web.base.service.impl.BaseServiceImpl;
import com.dtguai.web.common.error.ErrorCode;
import com.dtguai.web.common.exception.DefinedException;
import com.dtguai.web.util.FileUtil;
import com.dtguai.web.web.fastDfs.model.SysDefFdfs;
import com.dtguai.web.web.fastDfs.service.SysDefFdfsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Optional;

/**
 * fdfs
 *
 * @author guo
 * @date 2019-06-28 17:32:43
 */
@Service("sysDefFdfsService")
@Slf4j
public class SysDefFdfsServiceImpl extends BaseServiceImpl<SysDefFdfs> implements SysDefFdfsService {

    @Autowired
    private FastDfsServiceImpl fastDfsService;

    @Value("${sys.fdfsHttpHost}")
    private String fdfsHttpHost;

    /**
     * 上传
     *
     * @param file file
     * @return int
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysDefFdfs upload(MultipartFile file) {
        InputStream inputStream = null;
        try {
            long start = System.currentTimeMillis();
            inputStream = file.getInputStream();
            long attachSize = file.getSize();
            String fastFileId = fastDfsService.uploadFile(inputStream, attachSize, FileUtil.getFileNameEx(file.getOriginalFilename()));
            if (StringUtils.isBlank(fastFileId)) {
                log.error("fdfs上传文件失败,文件file:{},大小:{},名称:{}", inputStream, attachSize, FileUtil.getFileNameEx(file.getOriginalFilename()));
                throw new DefinedException("上传失败！");
            }
            SysDefFdfs fdfs = new SysDefFdfs();
            fdfs.setGroupName(fastFileId.substring(0, fastFileId.indexOf('/')))
                    .setFastFileId(fastFileId)
                    .setName(new String(Optional.ofNullable(file.getOriginalFilename())
                            .map(String::getBytes)
                            .orElse("".getBytes()), StandardCharsets.UTF_8))
                    .setSize(Long.toString(attachSize))
                    .setUrl(fdfsHttpHost + fastFileId);

            insertSelective(fdfs);
            log.info("上传文件{}成功，耗时：{}ms", file.getName(), System.currentTimeMillis() - start);
            return fdfs;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new DefinedException(ErrorCode.FDFS_ERROR);
        } finally {
            IOUtils.closeQuietly(inputStream);
        }
    }

    /**
     * 下载
     *
     * @param fdfs fdfs
     * @return InputStream
     */
    @Override
    public InputStream download(SysDefFdfs fdfs) {
        // 下载附件
        return fastDfsService.downloadStream(fdfs.getGroupName(), fdfs.getFastFileId());
    }

    /**
     * 删除
     *
     * @param attachment attachment
     * @return int
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delete(SysDefFdfs attachment) {
        try {
            fastDfsService.deleteFile(attachment.getGroupName(), attachment.getFastFileId());
            return super.delete(attachment);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new DefinedException(ErrorCode.FDFS_ERROR);
        }
    }
}